# coding:utf-8
import sys
import os
from pathlib import Path

from PySide6.QtWidgets import (
    QFrame,
    QVBoxLayout,
    QMenu,
    QApplication,
    QWidget,
    QPushButton,
    QHBoxLayout,
)
from PySide6.QtCore import QPoint, Qt, QUrl
from qframelesswindow.webengine import FramelessWebEngineView

from ...config import config
from ...utils.webview_controller import WebviewController
from .entrance import Entrance
from ...scheduler_manager import scheduler


class DevToolsWindow(FramelessWebEngineView):
    def __init__(self, parent=None):
        super().__init__(parent=parent)
        self.setWindowTitle("开发者工具")
        self.resize(600, 600)


class DevToolsView(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent=parent)
        self.setWindowTitle("开发者工具")
        self.dev_tools_window = DevToolsWindow(self)
        self.resize(600, 600)
        # 设置窗口大小不可变
        self.setFixedSize(self.size())


class WebViewInterface(QFrame):

    def __init__(self, parent=None):
        super().__init__(parent=parent)
        self.setObjectName("webViewInterface")
        self.dev_tools_view = None
        # 添加连接状态标志
        self.is_local_connection = config.get("project", {}).get("is-production", True)

        # 插件目录
        self.plugins_dir = Path(os.getcwd()) / "plugins"
        self.plugins_dir.mkdir(exist_ok=True)

        self.webView = FramelessWebEngineView(self)
        self.html_path = (
            os.getcwd().replace("\\", "/")
            + "/resources/webview/entrance/dist/index.html"
        )
        self.remote_url = config.get("project", {}).get(
            "remote-url", "http://localhost:8080/"
        )

        # 创建WebviewController实例
        self.page = self.webView.page()
        self.controller = WebviewController(
            self.page, [Entrance], self.webView, scheduler
        )

        # 加载初始页面
        self.load_current_page()

        # 创建导航按钮
        self.back_button = QPushButton("⬅️", self)
        self.back_button.clicked.connect(self.webView.back)
        self.back_button.setFixedSize(40, 30)
        self.back_button.setEnabled(False)

        self.forward_button = QPushButton("➡️", self)
        self.forward_button.clicked.connect(self.webView.forward)
        self.forward_button.setFixedSize(40, 30)
        self.forward_button.setEnabled(False)

        self.reload_button = QPushButton("🔃", self)
        self.reload_button.clicked.connect(self.webView.reload)
        self.reload_button.setFixedSize(40, 30)

        self.home_button = QPushButton("🏠", self)
        self.home_button.clicked.connect(self.go_home)
        self.home_button.setFixedSize(40, 30)

        # 连接WebView的信号以更新按钮状态
        self.webView.urlChanged.connect(self.update_navigation_buttons)

        # 创建导航按钮布局
        self.nav_button_layout = QHBoxLayout()
        self.nav_button_layout.addWidget(self.back_button)
        self.nav_button_layout.addWidget(self.forward_button)
        self.nav_button_layout.addWidget(self.reload_button)
        self.nav_button_layout.addWidget(self.home_button)
        self.nav_button_layout.addStretch()
        self.nav_button_layout.setSpacing(5)

        self.vBoxLayout = QVBoxLayout(self)
        self.vBoxLayout.setContentsMargins(10, 48, 10, 10)
        self.vBoxLayout.addLayout(self.nav_button_layout)
        self.vBoxLayout.addWidget(self.webView)
        self.webView.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu)
        self.webView.loadFinished.connect(self.on_load_finished)
        self.webView.customContextMenuRequested.connect(self.show_context_menu)

        # 应用样式
        self.apply_styles()

    def apply_styles(self):
        """应用样式到按钮"""
        button_style = """
            QPushButton {
                border: none;
                padding: 5px 10px;
                font-family: 'Segoe UI', 'Microsoft YaHei';
                font-size: 14px;
                color: white;
                border-radius: 5px;
                background-color: #2c68c6;
            }
            QPushButton:hover {
                background-color: #3a75d8;
            }
            QPushButton:pressed {
                background-color: #1a56b0;
            }
            QPushButton:disabled {
                background-color: #6c757d;
                color: #adb5bd;
            }
        """

        nav_button_style = (
            button_style
            + """
            QPushButton {
                background-color: #6c757d;
            }
            QPushButton:hover {
                background-color: #5a6268;
            }
            QPushButton:pressed {
                background-color: #495057;
            }
        """
        )

        toggle_button_style = (
            button_style
            + """
            QPushButton {
                background-color: #0d6efd;
            }
            QPushButton:hover {
                background-color: #0b5ed7;
            }
            QPushButton:pressed {
                background-color: #0a58ca;
            }
        """
        )

        self.back_button.setStyleSheet(nav_button_style)
        self.forward_button.setStyleSheet(nav_button_style)
        self.reload_button.setStyleSheet(nav_button_style)
        self.home_button.setStyleSheet(nav_button_style)

    def go_home(self):
        """返回首页"""
        self.webView.load(QUrl(self.html_path))

    def update_navigation_buttons(self):
        """更新导航按钮状态"""
        self.back_button.setEnabled(self.webView.history().canGoBack())
        self.forward_button.setEnabled(self.webView.history().canGoForward())

    def load_current_page(self):
        """加载当前连接对应的页面"""
        if self.is_local_connection:
            self.webView.load(QUrl(self.html_path))
        else:
            self.webView.load(QUrl(self.remote_url))

    def on_load_finished(self, success):
        """页面加载完成后初始化开发者工具"""
        if success:
            # 预初始化开发者工具
            self.init_dev_tools()
            # 更新导航按钮状态
            self.update_navigation_buttons()

    def init_dev_tools(self):
        """初始化开发者工具"""
        if not self.dev_tools_view:
            self.dev_tools_view = DevToolsView()
            self.page.setDevToolsPage(self.dev_tools_view.dev_tools_window.page())

    def show_context_menu(self, pos: QPoint):
        """显示自定义右键菜单"""
        # 创建上下文菜单
        menu = QMenu(self)

        # 添加标准浏览器动作
        back_action = menu.addAction("后退")
        back_action.triggered.connect(self.webView.back)

        forward_action = menu.addAction("前进")
        forward_action.triggered.connect(self.webView.forward)

        reload_action = menu.addAction("重新加载")
        reload_action.triggered.connect(self.webView.reload)

        menu.addSeparator()

        # 添加开发者工具相关动作
        dev_tools_action = menu.addAction("打开开发者工具")
        dev_tools_action.triggered.connect(self.toggle_dev_tools)

        menu.addSeparator()

        menu.addSeparator()

        # 在鼠标位置显示菜单
        menu.exec(self.webView.mapToGlobal(pos))

    def toggle_dev_tools(self):
        """切换开发者工具窗口显示状态"""
        if not self.dev_tools_view:
            self.init_dev_tools()

        if self.dev_tools_view is None:
            return

        if self.dev_tools_view.dev_tools_window.isVisible():
            self.dev_tools_view.hide()
            self.dev_tools_view.dev_tools_window.hide()
        else:
            self.dev_tools_view.show()
            self.dev_tools_view.dev_tools_window.show()
            self.dev_tools_view.dev_tools_window.raise_()  # 将窗口置于最前

    def closeEvent(self, event):
        """关闭时清理资源"""
        # 停止controller中的定时器
        # self.controller.bridge.timer.stop()
        if self.dev_tools_view:
            self.dev_tools_view.close()
        super().closeEvent(event)


if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = WebViewInterface()
    window.resize(1000, 700)
    window.show()
    sys.exit(app.exec())
